import { debounce } from 'lodash-es'
import { onMounted, onUnmounted } from 'vue'

/**
 * 封装大屏缩放方案
 * @param container 大屏元素选择器
 * @param designOption 设计稿尺寸
 * 注意：大屏宽高固定为设计稿宽高
 *
 * */
export default function useScreenScale(
  container: string,
  designOption = {
    width: 1920,
    height: 1080,
  },
) {
  let containerElement = null
  const { width, height } = designOption

  onMounted(() => {
    init()
  })

  function init() {
    containerElement = document.querySelector(container)
    if (!containerElement) return
    // 设置默认样式
    setElementStyle()
    // 初始缩放
    initScale()
    // 监听窗口变化，同步缩放
    addEventListener('resize', debounce(initScale, 200))
  }

  function setElementStyle() {
    Object.assign(containerElement.style, {
      width: `${width}px`,
      height: `${height}px`,
      transformOrigin: `top left`,
      transition: `transform 0.5s`,
    })
  }

  function initScale() {
    // 横纵坐标缩放的比例
    const scaleX = innerWidth / width
    const scaleY = innerHeight / height
    // 缩放的最小值
    const scale = Math.min(scaleX, scaleY)

    // 容器移动的距离，让容器居中
    const left = (innerWidth - width * scale) / 2
    const top = (innerHeight - height * scale) / 2
    containerElement.style.transform = `translate(${left}px, ${top}px) scale(${scale})`
  }

  onUnmounted(() => {
    removeEventListener('resize', debounce(initScale, 200))
    containerElement = null
  })
}
